import React, { Component } from 'react'

// 1.创建context对象,
// 2.每个class组件都有this.context
// 3.创建context对象是设置默认值
// 4.在子组件内部需要通过TestSon2.contextType = UserContext进行订阅
const UserContext = React.createContext({
  name: 'coderzjd',
})

export class Test extends Component {
  render() {
    return (
      <>
        <div>父组件</div>
        <hr />
        <UserContext.Provider value={{ name: 'coder' }}>
        <TestSon></TestSon>
        </UserContext.Provider>
        <hr />
        {/* 此处没有顶层provider使用创建context的默认值 */}
        <TestSon></TestSon>
      </>
    )
  }
}
export class TestSon extends Component {
  render() {
    return (
      <>
        <div>子组件1</div>
        <TestSon2></TestSon2>
      </>
    )
  }
}

export class TestSon2 extends Component {
  render() {
    console.log(this.context)
    return (
      <>
        <div>子组件2</div>
        {this.context.name}
      </>
    )
  }
}
TestSon2.contextType = UserContext
